package cn.tedu.cake.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author：GuoYaFeng
 * @Package：cn.tedu.cake.controller
 * @Project：cake1
 * @name：uploadController
 * @Date：2023/3/18 19:22
 * @Filename：uploadController
 */
@RestController
public class UploadController {
    @Value("d:/files")
    private String dirPath;

    @PostMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        String fileName = picFile.getOriginalFilename();
        //得到后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;

        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        File dirFile = new File(dirPath + datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        picFile.transferTo(new File(dirPath+datePath+fileName));
        return datePath+fileName;
    }

    @PostMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }

}
